package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dto.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import io.seata.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;

    /*
    * TODO 上传素材
    *  */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //TODO 校验参数 ( 存在  )    后缀检查: jpg  png   jpeg  gif
        if (multipartFile==null||multipartFile.getSize()==0){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确文件");
        }

        //TODO 用户是否登录 threadlocal.get
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录后再操作");
        }
        //TODO 2. 上传文件到OSS
        //todo 获取原始文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        //todo 检查上传文件的格式
        if (!checkFileSuffix(originalFilename)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }
        String fileId=null;
        try {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileId = fileStorageService.store(prefix, uuid + suffix, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"服务器异常，上传文件失败");
        }
        //TODO 3. 向wmMaterial新增一条数据
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setType((short)0);
        wmMaterial.setIsCollection((short)0); // 0 未收藏  1 收藏
        wmMaterial.setCreatedTime(new Date());
        //TODO 4. 返回结果  将保存成功的素材 回显给前端  记得将 url 路径添加访问前缀
        wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        return ResponseResult.okResult(wmMaterial);
    }
    private boolean checkFileSuffix(String path) {
        if (StringUtils.isBlank(path))
            return false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAllow=false;
        for (String suffix : allowSuffix) {
            if (path.endsWith(suffix)){//todo endsWith(suffix)以指定方式结尾
                isAllow=true;
                break;
            }
        }
        return isAllow;
    }

    /*
    * todo 查询素材列表
    *  */
    @Override
    public ResponseResult findList(WmMaterialDTO wmMaterialDTO) {
        //TODO 参数校验
        wmMaterialDTO.checkParam();
        //TODO 执行业务查询
        LambdaQueryWrapper<WmMaterial> lambdaQuery = Wrappers.lambdaQuery();
        if (wmMaterialDTO.getIsCollected() !=null&&wmMaterialDTO.getIsCollected()==1){
            lambdaQuery.eq(WmMaterial::getIsCollection,wmMaterialDTO.getIsCollected());
        }
        //TODO 当前登录用户的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        lambdaQuery.eq(WmMaterial::getUserId,user.getId());

        //TODO 时间倒序
        lambdaQuery.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> pageParam = new Page<>(wmMaterialDTO.getPage(),wmMaterialDTO.getSize());
        IPage<WmMaterial> resultPage = page(pageParam, lambdaQuery);
        List<WmMaterial> records = resultPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }
        //TODO 3 封装结果
        PageResponseResult pageResponseResult = new PageResponseResult(wmMaterialDTO.getPage(), wmMaterialDTO.getSize(), resultPage.getTotal());
        pageResponseResult.setData(records);
        return pageResponseResult;
    }

    /*
    * TODO 删除素材
    *  */
    @Override
    public ResponseResult delPicture(Integer id) {
        //TODO 参数校验
        if (id==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //TODO 业务处理
        //todo 判断当前id是否被引用，如果被引用则禁止删除
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(lambdaQuery);
        if (count>0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前图片已被引用");
        }
        //todo 删除素材库
        removeById(id);
        //todo 删除oss
        fileStorageService.delete(wmMaterial.getUrl());
        //TODO 封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /*
    * todo 素材的收藏与取消收藏
    *  */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //TODO  1.检查参数
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"id不能为空");
        }
        //todo 检查状态是否正确
        if (type.intValue()!=0&&type.intValue()!=1){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"收藏状态有误");
        }
        //TODO 2.更新状态
        //todo 获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,uid));
        return ResponseResult.okResult();
    }

}
